'use client'
import { useEffect, useRef } from "react";
import World from "./firework/World";
import rand from "./firework/rand";

export default function Home() {
  const ref_canvas = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    const canvas = ref_canvas.current
    if (!canvas) return;

    const world = new World(canvas);
    world.start();

    const on_pointerdown = (e: PointerEvent) => {
      const { left, top, width, height } = canvas.getBoundingClientRect();
      const firework = world.spawn_firework(width / 2, height, e.pageX - left, e.pageY - top);
      firework.show_target = true
    }
    canvas.addEventListener('pointerdown', on_pointerdown);

    const timer_id = setInterval(() => {
      let i = Math.floor(rand(1, 5))
      while ((--i) >= 0) {
        const { width, height } = canvas.getBoundingClientRect();
        const x = rand(0, width)
        world.spawn_firework(
          x + rand(-50, 50),
          height,
          x,
          rand(0, height)
        );
      }
    }, 100)

    return () => {
      world.destory()
      canvas.removeEventListener('pointerdown', on_pointerdown);
      clearInterval(timer_id);
    };
  }, [])
  return (
    <canvas ref={ref_canvas} style={{ width: '100vw', height: '100vh', userSelect: 'none' }} draggable={false} />
  );
}
